package com.py.base.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.py.base.entity.TableListModel;
import com.py.base.entity.TableModel;
import com.py.base.service.SysGeneratorService;
import com.py.base.utils.Query;

/**
 * 导出表结构
 * 
 * @author xucheng
 * @email xuqiao2016@126.com
 * @date 2021年6月19日 下午9:12:58
 */
@Controller
@RequestMapping("/excle")
public class ExcelController {
	@Autowired
	private SysGeneratorService sysGeneratorService;
  
	/**
	 * 生成代码
	 */
	@RequestMapping("/excelWriter")
   
	public void code(HttpServletRequest request, HttpServletResponse response) throws IOException{
		//初始化excel
		response.setContentType("application/vnd.ms-excel");
	    String fileName = "系统表结构" + ".xlsx";
	    response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
	    ExcelWriter excelWriter = null;
    
        try{
        	excelWriter = EasyExcel.write(response.getOutputStream()).build();
			List<TableListModel> list = sysGeneratorService.queryTbaleList();
			WriteTable writeTable = EasyExcel.writerTable(0).head(TableListModel.class).needHead(true).build();
			WriteSheet writeSheet = EasyExcel.writerSheet("表清单").build();
			excelWriter.write(list, writeSheet, writeTable);
			int i=1;
			for(TableListModel tableListModel : list){
				writeTable = EasyExcel.writerTable(i).head(TableModel.class).needHead(true).build();
				i++;
				String tablename    = tableListModel.getTableName();
				String tablenameCN    = tableListModel.getTableComment();
				List<TableModel> listT = sysGeneratorService.queryExcelColumnsList(tablename); 
				//
			    writeSheet = EasyExcel.writerSheet(tablenameCN+"("+tablename+")").build();
			    excelWriter.write(listT, writeSheet, writeTable);
			} 
			excelWriter.finish();
            response.flushBuffer();
        }catch(Exception e){

            e.printStackTrace();
        }
	}
}
 